package com.browsesoft.tools;

import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLContextModel;

/**
 * 显示周开始结束时间的model
 */
public class HTMLWeekContextModel implements HTMLContextModel {
	Calendar calendar = new GregorianCalendar();

	/**
	 * 年份
	 */

	private int year = calendar.get(Calendar.YEAR);

	/**
	 * 这周是这一年的第几周
	 */
	private int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);

	/**
	 * 构造函数
	 */
	public HTMLWeekContextModel() {
	}

	/**
	 * 得到内容
	 * 
	 * @return 内容
	 */
	public String getContext() {
		// 返回本周时间串
		// String start = monday.toString(); //this.format
		// String end = monday.getCalendarAfterDay(6).toString(); //this.format
		String result = null;
		result = year + "年 " + "第" + weekOfYear + "周";
		return result;
	}

	/**
	 * 初始化
	 * 
	 * @param request
	 *            请求
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
		// 得到系统当前所在周的起始日期
		// monday = BSCalendar.now().getMonday();
	}

	/**
	 * 处理请求
	 * 
	 * @param request
	 *            请求
	 * @param response 响应
	 * @throws Exception
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 如果是点击了下一周
		if (request.getParameter("week") != null) {
			String value = request.getParameter("week");
			if (value.equals("previous")) {
				this.setPreviousWeek();
			} else if (value.equals("next")) {
				this.setNextWeek();
			} else if (value.equals("today")) {
				this.setTodayWeek();
			}
			// 查询指定的年中的指定的周
			else if (value.equals("search")) {
				// 从页面上获得指定的
				this.year = Integer
						.parseInt(request.getParameter("searchyear"));
				this.weekOfYear = Integer.parseInt(request
						.getParameter("searchweek"));
			}
		}// end_if
	}

	/**
	 * 设置组件
	 * 
	 * @param component
	 *            组件
	 */
	public void setComponent(HTMLBasicComponent component) {
	}

	/**
	 * 更新元素
	 * 
	 * @param c
	 *            组件
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	/**
	 * 把时间调到下一周
	 */
	public void setNextWeek() {
		this.calendar.add(Calendar.DAY_OF_YEAR, 7);
		year = this.calendar.get(Calendar.YEAR);
		this.weekOfYear = this.calendar.get(Calendar.WEEK_OF_YEAR);
	}

	/**
	 * 把时间调到上一周
	 */
	public void setPreviousWeek() {
		this.calendar.add(Calendar.DAY_OF_YEAR, -7);
		year = this.calendar.get(Calendar.YEAR);
		this.weekOfYear = this.calendar.get(Calendar.WEEK_OF_YEAR);
	}

	/**
	 * 把时间跳动当前周
	 */
	public void setTodayWeek() {
		this.calendar = new GregorianCalendar();
		year = this.calendar.get(Calendar.YEAR);
		this.weekOfYear = this.calendar.get(Calendar.WEEK_OF_YEAR);
	}
}